﻿namespace Digitalmes.Core.Common.Extensions;

public static partial class HttpClientExtensions
{
    /// <summary>
    /// 尝试调用 GET 方法请求指定的资源，以 JSON 对象返回并进行反序列化。
    /// </summary>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="requestUri">请求的资源</param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public static async Task<(bool ok, TValue? result, Exception? ex)> TryGetJsonAsync<TValue>(this HttpClient client, 
        [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri, 
        CancellationToken cancellationToken = default)
    {
        try
        {
            var result = await client.GetJsonAsync<TValue>(requestUri, cancellationToken);
            return (true, result, default);
        }
        catch (Exception ex)
        {
            return (false, default, ex);
        }
    }

    /// <summary>
    /// 尝试调用 POST 方法请求指定的资源，以 JSON 对象返回并进行反序列化。
    /// </summary>
    /// <typeparam name="TRequest"></typeparam>
    /// <typeparam name="TResponse"></typeparam>
    /// <param name="requestUri">请求的资源</param>
    /// <param name="request">请求数据，会序列化成 JSON 对象。</param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public static async Task<(bool ok, TResponse? result, Exception? ex)> TryPostJsonAsync<TRequest, TResponse>(this HttpClient client,
        [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri,
        TRequest request,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var result = await client.PostJsonAsync<TRequest, TResponse>(requestUri, request, cancellationToken);
            return (true, result, default);
        }
        catch (Exception ex)
        {
            return (false, default, ex);
        }
    }

    /// <summary>
    /// 尝试调用 PUT 方法请求指定的资源，以 JSON 对象返回并进行反序列化。
    /// </summary>
    /// <typeparam name="TRequest"></typeparam>
    /// <typeparam name="TResponse"></typeparam>
    /// <param name="requestUri">请求的资源</param>
    /// <param name="request">请求数据，会序列化成 JSON 对象。</param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public static async Task<(bool ok, TResponse? result, Exception? ex)> TryPutJsonAsync<TRequest, TResponse>(this HttpClient client,
        [StringSyntax(StringSyntaxAttribute.Uri)] string? requestUri,
        TRequest request,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var result = await client.PutJsonAsync<TRequest, TResponse>(requestUri, request, cancellationToken);
            return (true, result, default);
        }
        catch (Exception ex)
        {
            return (false, default, ex);
        }
    }
}
